package ma.platform.server.student.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import ma.platform.server.core.util.R;
import ma.platform.server.core.constants.TokenConstant;
import ma.platform.server.core.context.LoginUserContext;
import ma.platform.server.student.entity.TbParent;
import ma.platform.server.student.req.WeappLoginReq;
import ma.platform.server.student.service.TbParentService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/wx/login")
@Tag(description = "微信登录模块", name = "微信登录模块")
public class WxLoginController {

    @Resource
    private WxMaService wxMaService;

    @Resource
    private TbParentService tbParentService;


    @PostMapping("/weapp")
    public R wxLogin(@RequestBody WeappLoginReq req) throws WxErrorException {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(req.getCode());
        String openId = sessionInfo.getOpenid();
        TbParent tbParent = tbParentService.getOne(Wrappers.<TbParent>lambdaQuery().eq(TbParent::getOpenId, openId).last("limit 1"));
        if (Objects.isNull(tbParent)) {
            tbParent = new TbParent();
            tbParent.setOpenId(openId);
            tbParentService.save(tbParent);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", tbParent.getId());
        String token = JWTUtil.createToken(map, TokenConstant.tokenKey.getBytes());
        return R.ok(token);
    }

    @PostMapping("/updateUserInfo")
    public R updateInfo(@RequestBody TbParent tbParent) {
        return R.ok(tbParentService.updateById(tbParent));
    }

    @GetMapping("/userInfo")
    public R getUserInfo() {
        return R.ok(tbParentService.getById(LoginUserContext.getUser().getId()));
    }
}
